package com.fesine.learn.design.pattern.creational.singleton;

import java.io.Serializable;

/**
 * @description: 饿汉模式
 * @author: fesine
 * @createTime:2019/4/2
 * @update:修改内容
 * @author: fesine
 * @updateTime:2019/4/2
 */
public class HungrySingleton implements Serializable {
    //private final static HungrySingleton hungrySingleton = new HungrySingleton();
    private final static HungrySingleton hungrySingleton;
    private static final long serialVersionUID = -7669913769399907877L;

    static {
        hungrySingleton = new HungrySingleton();
    }

    private HungrySingleton(){
        //避免通过反射获取单例新实例，此方法同样适用于静态内部类实现
        if(hungrySingleton != null){
            throw new RuntimeException("单例构造器禁止反射调用");
        }
    }

    public static HungrySingleton getInstance(){
        return hungrySingleton;
    }

    /**
     * 添加此方法后，通过序列化也会得到同一对象
     * 但在内存中也还是生成了两个对象，只是返回的时候只返回当前实例
     * @return
     */
    private Object readResolve(){
        return hungrySingleton;
    }
}
